import {
	HTTP_REQUEST_URL,
	HEADER,
	BASE_CONFIG,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from '../store';
import {getTerminal,isWxMp} from "./util";


// TODO 临时解决 uniapp 在小程序，undefined 会被 tostring 的问题
function deleteUndefinedProperties(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        deleteUndefinedProperties(obj[key]); // 递归调用，处理嵌套的对象
      } else if (obj[key] === undefined) {
        delete obj[key];
      }
    }
  }
}

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = true,
	noVerify = false
}, params) {
	let header = HEADER

	if (params !== undefined) {
		header = HEADERPARAMS;
	}

	if (isWxMp()){
		header['app-id'] = BASE_CONFIG.appId
	}

	if (!noAuth) {
		//登录过期自动登录
		if (!store.state.app.token && !checkLogin()) {
      // debugger
			toLogin();
			return Promise.reject({
				msg: '未登录'
			});
		}
	}

  deleteUndefinedProperties(data)

  if (url.indexOf('app-api') >= 0) {
    header = {
      ...header
    }
  }
  	// 终端
	header['terminal'] = getTerminal()
	if (store.state.app.token) {
    header[TOKENNAME] = 'Bearer ' + store.state.app.token;
  }
	return new Promise((reslove, reject) => {
		console.log('url---',HTTP_REQUEST_URL)
		// console.log('BASE_CONFIG---',BASE_CONFIG)
		uni.request({
      url: HTTP_REQUEST_URL + url,
      method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.code === 200 || res.data.code === 0)
					reslove(res.data, res);
				else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
					toLogin();
					reject(res.data);
				} else
					uni.showToast({
						icon: 'none',
						title: res.data.msg || res.data.message || '系统繁忙'
					})
					reject(res.data.msg || res.data.message || '系统繁忙');
			},
			fail: (msg) => {
				reject('请求失败',msg);
			},
			complete:()=>{
				let curlParts = [`curl -X ${(method || 'GET').toUpperCase()}`];

				for (const key in header) {
					curlParts.push(`-H "${key}: ${header[key]}"`);
				}

				if (['POST', 'PUT', 'PATCH'].includes(method.toUpperCase()) && data) {
					try {
						curlParts.push(`-d '${JSON.stringify(data)}'`);
					} catch (e) {
						console.warn('❗️无法序列化 data 为 JSON');
					}
				}

				curlParts.push(`"${HTTP_REQUEST_URL + url}"`);

				console.log('📦 CURL 请求输出:\n\n' + curlParts.join(' \\\n  '));
				console.log("\n")
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});


uni.addInterceptor('request', {
	invoke(args) {
		if (args.header) {
			delete args.header['Referer'];
			delete args.header['referer'];
		}
	}
});


export default request;
